<template>
  <div class="write-container">
    <div class="write-header">
      <h1>写文章</h1>
      <div class="header-actions">
        <a-space>
          <a-button @click="handleSaveDraft" :loading="draftLoading">
            保存草稿
          </a-button>
          <a-button 
            type="primary" 
            @click="handlePublish"
            :loading="publishLoading"
          >
            发布文章
          </a-button>
        </a-space>
      </div>
    </div>

    <a-form
      :model="formData"
      :rules="rules"
      @finish="handlePublish"
      layout="vertical"
      class="write-form"
    >
      <a-form-item label="文章标题" name="title">
        <a-input
          v-model:value="formData.title"
          placeholder="请输入文章标题"
          size="large"
          class="title-input"
        />
      </a-form-item>

      <a-form-item label="文章摘要" name="excerpt">
        <a-textarea
          v-model:value="formData.excerpt"
          placeholder="请输入文章摘要（可选）"
          :rows="3"
          :maxlength="200"
          show-count
        />
      </a-form-item>

      <a-form-item label="文章内容" name="content">
        <div class="editor-container">
          <a-textarea
            v-model:value="formData.content"
            placeholder="开始写作吧..."
            :rows="20"
            class="content-editor"
          />
        </div>
      </a-form-item>

      <a-form-item label="文章标签" name="tags">
        <a-select
          v-model:value="formData.tags"
          mode="multiple"
          placeholder="选择标签"
          :options="tagOptions"
          class="tags-select"
        />
      </a-form-item>

      <a-form-item label="文章分类" name="category">
        <a-select
          v-model:value="formData.category"
          placeholder="选择分类"
          :options="categoryOptions"
          class="category-select"
        />
      </a-form-item>

      <a-form-item label="文章封面">
        <a-input
          v-model:value="formData.coverImage"
          placeholder="请输入封面图片URL"
        />
        <FileUpload />
      </a-form-item>

      <a-form-item label="发布设置">
        <a-space direction="vertical" style="width: 100%">
          <a-checkbox v-model:checked="formData.isTop">
            置顶文章
          </a-checkbox>
          <a-checkbox v-model:checked="formData.isRecommend">
            推荐文章
          </a-checkbox>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores'
import { postApi, categoryApi, tagApi } from '@/api'
import type { PostRequest, Category, Tag } from '@/types'
import FileUpload from './FileUpload.vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const draftLoading = ref(false)
const publishLoading = ref(false)
const categories = ref<Category[]>([])
const tags = ref<Tag[]>([])

// 表单数据
const formData = reactive({
  title: '',
  excerpt: '',
  content: '',
  coverImage: '',
  tags: [] as number[],
  category: undefined as number | undefined,
  isTop: 0,
  isRecommend: 0
})

// 标签选项
const tagOptions = ref<{ label: string; value: number }[]>([])

// 分类选项
const categoryOptions = ref<{ label: string; value: number }[]>([])

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在5到100个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    { min: 10, message: '文章内容至少10个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ]
}

// 加载分类和标签数据
const loadOptions = async () => {
  try {
    const [categoriesResponse, tagsResponse] = await Promise.allSettled([
      categoryApi.getCategoryList({ page: '1', size: '100' }),
      tagApi.getTagList({ pageNo: '1', pageSize: '100' })
    ])
    
    if (categoriesResponse.status === 'fulfilled') {
      categories.value = categoriesResponse.value.data.result || []
      categoryOptions.value = categories.value.map(cat => ({
        label: cat.name,
        value: cat.id
      }))
    }
    
    if (tagsResponse.status === 'fulfilled') {
      tags.value = tagsResponse.value.data.result || []
      tagOptions.value = tags.value.map(tag => ({
        label: tag.name,
        value: tag.id
      }))
    }
  } catch (error) {
    console.error('加载选项数据失败:', error)
  }
}

// 保存草稿
const handleSaveDraft = async () => {
  if (!formData.title && !formData.content) {
    message.warning('请至少输入标题或内容')
    return
  }
  
  draftLoading.value = true
  
  try {
    const postData = {
      userId: userStore.userInfo?.id?.toString() || '1',
      title: formData.title,
      content: formData.content,
      excerpt: formData.excerpt,
      coverImage: formData.coverImage,
      status: 'DRAFT',
      isTop: formData.isTop ? 1 : 0,
      isRecommend: formData.isRecommend ? 1 : 0,
      categoryId: formData.category || 1,
      tagIds: formData.tags
    }
    
    await postApi.createPost(postData)
    message.success('草稿保存成功')
  } catch (error) {
    message.error('保存草稿失败')
  } finally {
    draftLoading.value = false
  }
}

// 发布文章
const handlePublish = async () => {
  if (!userStore.userInfo?.id) {
    message.error('请先登录')
    return
  }
  
  publishLoading.value = true
  
  try {
    const postData = {
      userId: userStore.userInfo.id.toString(),
      title: formData.title,
      content: formData.content,
      excerpt: formData.excerpt,
      coverImage: formData.coverImage,
      status: 'PUBLISHED',
      isTop: formData.isTop ? 1 : 0,
      isRecommend: formData.isRecommend ? 1 : 0,
      categoryId: formData.category || 1,
      tagIds: formData.tags
    }
    
    await postApi.createPost(postData)
    message.success('文章发布成功！')
    router.push('/')
  } catch (error) {
    message.error('发布失败，请重试')
  } finally {
    publishLoading.value = false
  }
}

onMounted(() => {
  loadOptions()
})
</script>

<style scoped>
.write-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
}

.write-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.write-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.write-form {
  background: white;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.title-input {
  font-size: 18px;
  font-weight: 500;
}

.editor-container {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.content-editor {
  border: none;
  resize: none;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  line-height: 1.6;
}

.content-editor:focus {
  box-shadow: none;
}

.tags-select,
.category-select {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .write-container {
    padding: 16px;
  }
  
  .write-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .write-form {
    padding: 20px;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .header-actions .ant-space {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
